package com.example.com.netty.handle;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author 杜豪波
 * @description: TODO
 * @date 2020/1/3 15:38
 */
public class NettyTCPHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(NettyTCPHandler.class);

    /**
     * @function 接收处理
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
            throws Exception {
        // 统一处理数据

    }

    /**
     * @function 激活渠道
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx)
            throws Exception {
        logger.debug("TCP信道激活渠道,信道编号:" + ctx.channel().id());
        ctx.fireChannelActive();
    }

    /**
     * @function 未激活渠道
     */
    @Override
    public void channelInactive(ChannelHandlerContext ctx)
            throws Exception {
        logger.debug("TCP信道未激活渠道,信道编号:" + ctx.channel().id());
        ctx.fireChannelInactive();
    }

    /**
     * @function 异常处理
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        logger.debug("TCP信道连接异常,信道编号:" + ctx.channel().id());
    }

    /**
     * @author clq
     * @function 心跳请求处理
     * @date 2017-12-25
     */
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object obj) throws Exception {
        if (obj instanceof IdleStateEvent) {
            IdleStateEvent event = (IdleStateEvent) obj;
            // 如果读通道处于空闲状态,说明没有接收到心跳命令
            if (IdleState.READER_IDLE.equals(event.state())){
            }
        } else {
            super.userEventTriggered(ctx, obj);
        }
    }

}
